<template>
  <div class="main">
    <div class="left-title" @click="handleLook"
      ><img src="@/assets/images/file.png" />
      <span class="fileTitle">{{ props.fileName?.split('.')[0] || checkItem?.label }}</span></div
    >
    <div class="actions">
      <!-- 消防 -->
      <a-space v-if="checkItem?.type == 'fire'">
        <a-button
          type="link"
          @click="handleAdd"
          v-if="!props.url && props.isShow && checkItem?.needCreate"
          :disabled="props.disabled"
          >制作</a-button
        >
        <a-upload
          :action="`${actionUrl}/manage/upload/uploadFile/${!props.isLicense ? '4' : '5'}`"
          accept="image/*"
          :maxCount="1"
          :headers="uploadHeader"
          :showUploadList="false"
          @change="handleUploadFire"
          :before-upload="beforeUpload"
          v-if="!props.url && checkItem?.needUpload"
        >
          <a-button type="link">上传</a-button>
        </a-upload>
        <a-button type="link" @click="handleDown" v-if="props.url">下载</a-button>
        <a-button type="link" @click="handleDelete" v-if="props.url && props.isShow">删除</a-button>
      </a-space>
      <!-- 案件 -->
      <a-space v-if="checkItem?.type == 'case'">
        <a-button
          type="link"
          @click="handleAdd"
          :disabled="props.disabled"
          v-if="!props.url && checkItem?.needCreate && props.isShow"
          >制作</a-button
        >
        <a-upload
          :action="`${actionUrl}/manage/upload/uploadFile/${!props.isLicense ? '4' : '5'}`"
          accept="image/*"
          :maxCount="1"
          :headers="uploadHeader"
          :showUploadList="false"
          @change="handleUpload"
          :before-upload="beforeUpload"
          v-if="
            (checkItem?.needCreate && props.url && !props.newFileUrl && props.isShow) ||
            (!checkItem?.needCreate && !props.newFileUrl && props.isShow)
          "
        >
          <a-button type="link">上传</a-button>
        </a-upload>

        <a-button
          type="link"
          @click="handleDown"
          v-if="
            props.newFileUrl ||
            (props.url && checkItem?.needDown) ||
            (props.url && checkItem?.needCreate)
          "
          >下载</a-button
        >
        <a-button
          type="link"
          @click="handleDelete"
          v-if="(props.newFileUrl || (props.url && checkItem?.needCreate)) && props.isShow"
          >删除</a-button
        >
      </a-space>
      <!-- 检查结果表 -->
      <a-space v-if="checkItem?.type == 'download'">
        <a-button type="link" @click="handleDown">下载</a-button>
      </a-space>
    </div>
  </div>

  <a-modal
    :title="'文书制作'"
    v-model:open="open"
    :width="
      props.type == 6 || props.type == 9 || props.type == 10
        ? 400
        : props.type == 1 || props.type == 18
        ? 950
        : 910
    "
    @ok="handleOk"
    class="fileModal"
  >
    <AdministrativePenalty
      v-if="props.type == 1"
      :id="props.caseId"
      ref="administrativePenalty"
      @getDataUrl="getDataUrl"
    />
    <NowAdministrativePenalty
      v-if="props.type == 2"
      :id="props.caseId"
      ref="administrativePenalty"
      @getDataUrl="getDataUrl"
    />
    <SafetyInspection
      v-if="props.type == 3"
      ref="administrativePenalty"
      :id="props.id"
      @getDataUrl="getDataUrl"
    />
    <ImmediateRectification
      v-if="props.type == 4"
      :id="props.id"
      ref="administrativePenalty"
      @getDataUrl="getDataUrl"
    />
    <CorrectTimeLimit
      v-if="props.type == 5"
      :id="props.id"
      ref="administrativePenalty"
      @getDataUrl="getDataUrl"
    />
    <BeCurrent v-if="props.type == 6" ref="administrativePenalty" @getDataUrl="getDataUrl" />
    <EvidenceCollection
      v-if="props.type == 7"
      :id="props.caseId"
      ref="administrativePenalty"
      @getDataUrl="getDataUrl"
    />
    <RecordForm v-if="props.type == 8" ref="administrativePenalty" @getDataUrl="getDataUrl" />
    <InspectionRecords
      v-if="props.type == 9"
      ref="administrativePenalty"
      @getDataUrl="getDataUrl"
    />
    <SupervisionRecords
      v-if="props.type == 10"
      ref="administrativePenalty"
      @getDataUrl="getDataUrl"
    />
    <NotificationRecord
      v-if="props.type == 11"
      :id="props.caseId"
      ref="administrativePenalty"
      @getDataUrl="getDataUrl"
    />
    <NoticeInquiry
      v-if="props.type == 12"
      :id="props.caseId"
      ref="administrativePenalty"
      @getDataUrl="getDataUrl"
    />
    <GuidanceProposal
      v-if="props.type == 18"
      :id="props.id"
      ref="administrativePenalty"
      @getDataUrl="getDataUrl"
    />
    <FireSafetyGuidanceLetter
      v-if="props.type == 21"
      :id="props.id"
      ref="administrativePenalty"
      @getDataUrl="getDataUrl"
    />
    <PenaltyDecision
      v-if="props.type == 27"
      :id="props.caseId"
      ref="administrativePenalty"
      @getDataUrl="getDataUrl"
    />
    <CaseTermination
      v-if="props.type == 28"
      :id="props.caseId"
      ref="administrativePenalty"
      @getDataUrl="getDataUrl"
    />
  </a-modal>

  <a-modal
    v-model:open="fileOpen"
    title="文件预览"
    :width="800"
    :footer="null"
    :destroyOnClose="true"
  >
    <img v-if="fileType == 1" :src="pdfUrl" style="width: 100%; height: 100%; overflow: scroll" />
    <iframe
      v-if="fileType == 2"
      :src="pdfUrl + '#toolbar=0'"
      width="100%"
      style="height: 70vh; overflow: scroll"
    />
    <vue-office-docx v-if="fileType == 3" :src="pdfUrl" />
  </a-modal>
</template>
<script setup lang="ts">
  import AdministrativePenalty from './components/administrativePenalty/index.vue';
  import NowAdministrativePenalty from './components/nowAdministrativePenalty/index.vue';
  import SafetyInspection from './components/safetyInspection/index.vue';
  import ImmediateRectification from './components/immediateRectification/index.vue';
  import CorrectTimeLimit from './components/correctTimeLimit/index.vue';
  import BeCurrent from './components/beCurrent/index.vue';
  import RecordForm from './components/recordForm/index.vue';
  import InspectionRecords from './components/inspectionRecords/index.vue';
  import SupervisionRecords from './components/supervisionRecords/index.vue';
  import NotificationRecord from './components/notificationRecord/index.vue';
  import NoticeInquiry from './components/noticeInquiry/index.vue';
  import EvidenceCollection from './components/evidenceCollection/index.vue';
  import GuidanceProposal from './components/guidanceProposal/index.vue';
  import FireSafetyGuidanceLetter from './components/fireSafetyGuidanceLetter/index.vue';
  import PenaltyDecision from './components/penaltyDecision/index.vue';
  import CaseTermination from './components/caseTermination/index.vue';

  import { ref, onMounted, withDefaults, defineProps, watch } from 'vue';
  import { bookData } from './config';
  import {
    downloadFile,
    delDoc,
    uploadCaseFile,
    uploadLicenseFile,
    deleteCaseFile,
    deleteUploadCaseFile,
    uploadFireFile,
  } from '@/api/account';
  import { message, Upload } from 'ant-design-vue';
  import { Storage } from '@/utils/Storage';
  import { ACCESS_TOKEN_KEY } from '@/enums/cacheEnum';
  import VueOfficeDocx from '@vue-office/docx';

  defineOptions({
    name: '',
  });
  const uploadHeader = {
    'API-User-Token': Storage.get(ACCESS_TOKEN_KEY),
  };
  const emit = defineEmits(['getBookUrl']);
  const actionUrl = ref(import.meta.env.VITE_BASE_API);
  interface PropsDialog {
    type: number; //文书类型
    id?: any; // 任务id
    url?: any; // 文书地址
    newFileUrl?: any; // 签字后的地址
    disabled?: boolean; //是否可以点击
    caseId?: any; // 案件id
    caseFileId?: any; // 文书id
    isShow?: boolean;
    isLicense?: boolean; //是否是行政许可
    fileName?: string;
  }
  const props = withDefaults(defineProps<PropsDialog>(), {
    type: 1,
    id: '',
    url: '',
    newFileUrl: '',
    disabled: false,
    caseId: '',
    caseFileId: '',
    title: '',
    isShow: true,
    isLicense: false,
    fileName: '',
  });
  const open = ref(false);
  const administrativePenalty = ref();

  const checkItem = ref();
  onMounted(() => {
    checkItem.value = bookData.filter((item: any) => item.key == props.type)[0];
  });
  const handleAdd = () => {
    open.value = true;
  };
  const handleOk = () => {
    administrativePenalty.value.confirm();
  };
  const getDataUrl = (data) => {
    emit('getBookUrl', data);
    open.value = false;
  };
  const downFile = (url, name) => {
    var fileUrl = url; // 文件的URL
    var fileName = name; // 新的文件名

    var xhr = new XMLHttpRequest();
    xhr.open('GET', fileUrl, true);
    xhr.responseType = 'blob';

    xhr.onload = function () {
      if (xhr.status === 200) {
        var blob = xhr.response;
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
      }
    };

    xhr.send();
  };
  const handleDown = () => {
    // downloadFile(props.url).then((res) => {
    //   let blob = new Blob([res], {
    //     type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8',
    //   });
    //   let url = window.URL.createObjectURL(blob);
    //   console.log(url);
    //   const link = document.createElement('a'); // 创建a标签
    //   link.download = checkItem.value.label;
    //   link.href = url;
    //   link.click();
    //   URL.revokeObjectURL(url); // 释放内存
    // });
    if (props.newFileUrl) {
      const nameFix1 = props.newFileUrl.split('.')[props.newFileUrl.split('.').length - 1];
      downFile(
        `${import.meta.env.VITE_BASE_API}/manage/upload/downloadFile?fileUrl=${props.newFileUrl}`,
        `${checkItem.value.label}.${nameFix1}`,
      );
    } else {
      const nameFix2 = props.url.split('.')[props.url.split('.').length - 1];
      downFile(
        `${import.meta.env.VITE_BASE_API}/manage/upload/downloadFile?fileUrl=${props.url}`,
        `${checkItem.value.label}.${nameFix2}`,
      );
    }
  };
  const handleDelete = () => {
    if (props.id) {
      delDoc(checkItem.value.value, props.id).then((res) => {
        if (res.code == 0) {
          message.success('删除成功');
          emit('getBookUrl', res);
        }
      });
    } else if (props.caseFileId) {
      // 删除上传完的文书 / 询问笔录,其他

      if (props.newFileUrl && !checkItem.value.needDeleteReal) {
        deleteUploadCaseFile(props.caseFileId).then((res) => {
          if (res.code == 0) {
            message.success('删除成功');
            emit('getBookUrl', res);
          }
        });
      } else {
        // 删除文书
        deleteCaseFile(props.caseFileId).then((res) => {
          if (res.code == 0) {
            message.success('删除成功');
            emit('getBookUrl', res);
          }
        });
      }
    }
  };

  const beforeUpload = (file, fileList) => {
    const regex = /^image\/.+/;
    const isPDF = regex.test(file.type);
    if (!isPDF) {
      message.error(`只支持上传图片类型`);
    }
    return isPDF || Upload.LIST_IGNORE;
  };
  const handleUpload = (info) => {
    if (info.file.status === 'done') {
      message.success(`${info.file.name}上传成功`);
      let params = {
        id: props.caseFileId,
        caseId: props.caseId,
        fileType:
          props.type == 13
            ? 1
            : props.type == 7
            ? 2
            : props.type == 14
            ? 3
            : props.type == 24
            ? 4
            : props.type == 12
            ? 6
            : props.type == 15
            ? 7
            : props.type == 25
            ? 10
            : props.type == 11
            ? 12
            : props.type == 1
            ? 13
            : props.type == 26
            ? 15
            : props.type == 16
            ? 16
            : props.type == 22
            ? 17
            : props.type == 2
            ? 20
            : props.type == 29
            ? 131
            : props.type == 30
            ? 151
            : props.type == 31
            ? 191
            : '',
        //文件类型  1、立案审批表； 2、调查取证通知书； 3、权力义务告知书；4、先行登记保存决定书；
        // 5、调查取证其他文书；  6、询问通知书；7、询问笔录；8、询问笔录其他文书；9、集体议案相关文书；
        // 10、法制审核意见；11、其他相关文书；12、行政处罚告知笔录；13、行政处罚决定书； 14、不予行政处罚决定书；
        // 15、行政处罚延期/ 分期缴纳罚款决定书；16、送达回证；  17、缴纳凭证；18、终止案件集体议案相关文书；
        // 19、终止案件调查决定书；20、当场处罚决定书；
        newFileUrl: info.file.response.data.fileIds[0],
      };
      if (props.isLicense) {
        let licensePms = {
          id: props.id, //任务id
          taskStatus: 6, //处理类型 5、文书制作 6、送达回证
          type: '1', //0 非暂存 , 1 暂存
          fileUrl: info.file.response.data.fileIds[0], //仅送达回证时传值
        };
        uploadLicenseFile(licensePms).then((res) => {
          if (res.code == 0) {
            emit('getBookUrl', res);
          }
        });
      } else {
        uploadCaseFile(params).then((res) => {
          if (res.code == 0) {
            emit('getBookUrl', res);
          }
        });
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name}上传失败`);
    }
  };
  const handleUploadFire = (info) => {
    if (info.file.status === 'done') {
      message.success(`${info.file.name}上传成功`);
      let params = {
        id: props.id,
        fileUrl: info.file.response.data.fileIds[0],
        type: 1,
      };
      uploadFireFile(params).then((res) => {
        if (res.code == 0) {
          emit('getBookUrl', res);
        }
      });
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name}上传失败`);
    }
  };
  const fileOpen = ref(false);
  const pdfUrl = ref();
  const fileType = ref(1);
  const handleLook = () => {
    if (props.newFileUrl) {
      // 判断类型 img 1 pdf 2 docx 3
      const nameFix1 = props.newFileUrl.split('.')[props.newFileUrl.split('.').length - 1];
      if (nameFix1 === 'docx') {
        fileType.value = 3;
        downloadFile(props.newFileUrl).then((res) => {
          let blob = new Blob([res], {
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          }); //文件流处理
          const url = window.URL.createObjectURL(blob);
          pdfUrl.value = url;
          fileOpen.value = true;
        });
      } else if (nameFix1 === 'pdf') {
        fileType.value = 2;
        downloadFile(props.url).then((res) => {
          let blob = new Blob([res], { type: 'application/pdf' }); //文件流处理
          const url = window.URL.createObjectURL(blob);
          pdfUrl.value = url;
          fileOpen.value = true;
        });
      } else {
        fileType.value = 1;
        downloadFile(props.newFileUrl).then((res) => {
          let blob = new Blob([res], { type: 'image' }); //文件流处理
          const url = window.URL.createObjectURL(blob);
          pdfUrl.value = url;
          fileOpen.value = true;
        });
      }
    } else if (props.url) {
      if (!checkItem.value.needCreate && checkItem.value.key != 13) {
        return;
      }
      // 判断类型 img 1 pdf 2 docx 3 image
      const nameFix1 = props.url.split('.')[props.url.split('.').length - 1];
      if (nameFix1 === 'pdf') {
        fileType.value = 2;
        downloadFile(props.url).then((res) => {
          let blob = new Blob([res], { type: 'application/pdf' }); //文件流处理
          const url = window.URL.createObjectURL(blob);
          pdfUrl.value = url;
          fileOpen.value = true;
        });
      } else {
        fileType.value = 1;
        downloadFile(props.url).then((res) => {
          let blob = new Blob([res], { type: 'image' }); //文件流处理
          const url = window.URL.createObjectURL(blob);
          pdfUrl.value = url;
          fileOpen.value = true;
        });
      }
    }
  };
</script>

<style lang="less" scoped>
  .main {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 16px;

    .left-title {
      display: flex;
      align-items: center;
      color: #666;
      font-size: 14px;
      width: 80%;
      img {
        width: 30px;
        height: 30px;
      }

      .fileTitle {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }

    .actions {
      color: #1764ce;
    }
  }
</style>
